import { useCallback, useEffect, useRef } from 'react';
import { useSocketStore } from '../stores/socketStore';
import { useVoiceStore } from '../stores/voiceStore';

interface UseStreamingSpeechRecognitionOptions {
  language?: string;
  autoSend?: boolean;
  onFinalResult?: (text: string) => void;
}

export function useStreamingSpeechRecognition(options: UseStreamingSpeechRecognitionOptions = {}) {
  const { socket, isConnected } = useSocketStore();
  const {
    setRecognitionText,
    setError,
    startRecording,
    stopRecording,
    reset,
    settings
  } = useVoiceStore();

  const mediaRecorderRef = useRef<MediaRecorder | null>(null);
  const isRecordingRef = useRef(false);
  const audioStreamRef = useRef<MediaStream | null>(null);

  // 启动流式识别
  const start = useCallback(async () => {
    if (!isConnected) {
      setError('Socket 未连接，无法进行流式识别');
      return;
    }
    try {
      // 获取音频流
      const stream = await navigator.mediaDevices.getUserMedia({
        audio: {
          echoCancellation: settings.echoCancellation,
          noiseSuppression: settings.noiseReduction,
          autoGainControl: settings.autoGainControl,
          sampleRate: 16000
        }
      });
      audioStreamRef.current = stream;
      const recorder = new MediaRecorder(stream, { mimeType: 'audio/webm;codecs=opus' });
      mediaRecorderRef.current = recorder;
      isRecordingRef.current = true;
      startRecording();
      // 通知服务端开始流式识别
      socket?.emit('voice:stream/start', { language: options.language || settings.language });
      // 分片推送
      recorder.ondataavailable = (event: BlobEvent) => {
        if (event.data.size > 0 && isRecordingRef.current) {
          const reader = new FileReader();
          reader.onload = () => {
            const base64 = (reader.result as string).split(',')[1];
            socket?.emit('voice:stream/data', base64);
          };
          reader.readAsDataURL(event.data);
        }
      };
      recorder.start(200); // 每200ms分片
    } catch (e) {
      setError('无法获取麦克风权限或初始化录音: ' + (e instanceof Error ? e.message : String(e)));
    }
  }, [isConnected, socket, settings, options.language, startRecording, setError]);

  // 停止流式识别
  const stop = useCallback(() => {
    isRecordingRef.current = false;
    stopRecording();
    // 停止录音
    if (mediaRecorderRef.current && mediaRecorderRef.current.state === 'recording') {
      mediaRecorderRef.current.stop();
    }
    // 关闭音频流
    if (audioStreamRef.current) {
      audioStreamRef.current.getTracks().forEach(track => track.stop());
      audioStreamRef.current = null;
    }
    // 通知服务端结束
    socket?.emit('voice:stream/end');
  }, [stopRecording, socket]);

  // 监听服务端流式识别结果
  useEffect(() => {
    if (!socket) return;
    const onPartial = (data: any) => {
      setRecognitionText(data.partial || data.text || '', false, 0.7);
    };
    const onFinal = (data: any) => {
      setRecognitionText(data.text || '', true, 0.9);
      if (options.autoSend && data.text && options.onFinalResult) {
        setTimeout(() => options.onFinalResult!(data.text), 500);
      }
    };
    const onError = (data: any) => {
      setError(data.message || '流式识别失败');
      stop();
    };
    socket.on('voice:stream/partial', onPartial);
    socket.on('voice:stream/final', onFinal);
    socket.on('voice:stream/error', onError);
    return () => {
      socket.off('voice:stream/partial', onPartial);
      socket.off('voice:stream/final', onFinal);
      socket.off('voice:stream/error', onError);
    };
  }, [socket, setRecognitionText, setError, stop, options.autoSend, options.onFinalResult]);

  // 组件卸载时自动清理
  useEffect(() => {
    return () => {
      stop();
      reset();
    };
  }, [stop, reset]);

  return {
    start,
    stop,
    isRecording: isRecordingRef.current,
    // 识别文本和错误直接用 voiceStore 的 selector
  };
} 